package com.leetcode;

import com.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 113. 路径总和 II
 * 递归, 从顶到底的思维
 * 在list数组中运筹
 *
 * @author fy
 * @date 2022/4/24 17:54
 */
public class Solution113_1 {

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(root, targetSum, new ArrayList<>(), res);
        return res;
    }

    private void dfs(TreeNode node, int targetSum, List<Integer> path, List<List<Integer>> res) {
        if (node == null) {
            return;
        }
        path.add(node.val);
        int newTargetSum = targetSum - node.val;
        if (node.left == null && node.right == null) {
            if (newTargetSum == 0) {
                res.add(new ArrayList<>(path));
            }
            path.remove(path.size() - 1);
            return;
        }
        dfs(node.left, newTargetSum, path, res);
        dfs(node.right, newTargetSum, path, res);
        path.remove(path.size() - 1);
    }

}
